const OSS = require('ali-oss');
const config = require('../config/oss.config');

class OssService {
  constructor() {
    this.client = new OSS({
      region: config.region,
      accessKeyId: config.accessKeyId,
      accessKeySecret: config.accessKeySecret,
      bucket: config.bucket
    });
  }

  /**
   * 获取文件上传签名URL
   * @param {string} dir - 上传目录
   * @param {string} filename - 文件名
   * @returns {Object} 包含签名URL和文件完整路径
   */
  async getUploadSignedUrl(dir, filename) {
    try {
      const key = `${dir}/${Date.now()}-${filename}`;
      const url = await this.client.signatureUrl(key, {
        method: 'PUT',
        expires: 3600
      });

      return {
        url,
        key
      };
    } catch (error) {
      console.error('Failed to get upload signed URL:', error);
      throw error;
    }
  }

  /**
   * 获取文件访问签名URL
   * @param {string} filePath - 文件路径
   * @returns {string} 签名URL
   */
  async getAccessSignedUrl(filePath) {
    try {
      const signedUrl = await this.client.signatureUrl(filePath, {
        expires: 3600
      });

      return signedUrl;
    } catch (error) {
      console.error('Failed to get access signed URL:', error);
      throw error;
    }
  }

  /**
   * 删除文件
   * @param {string} filePath - 文件路径
   */
  async deleteFile(filePath) {
    try {
      await this.client.delete(filePath);
    } catch (error) {
      console.error('Failed to delete file:', error);
      throw error;
    }
  }
}

// Export both the class and a singleton instance
module.exports = {
  OssService,
  ossService: new OssService()
}; 